<template>
  <div>
    <div align="right" style="margin:0 0 10px 0">
      <div style="float:right"><a-button size="small" @click="printDiv">打印</a-button></div>
      <div style="float:right">
        <a-checkbox-group v-model="value" style="width: 100%">
          <a-checkbox value="1">表单</a-checkbox>
          <a-checkbox value="2">流程图</a-checkbox>
          <a-checkbox value="3">流程跟踪单</a-checkbox>
        </a-checkbox-group>
      </div>
    </div>
    <div style="clear:both" />
    <div ref="ddd" id="ddd" class="ca" />
    <div ref="imgwe" id="img" />
    <div ref="printDiv" id="printDiv" style="margin-top:20px">
      <div v-if="value.indexOf('1')!=-1">
        <k-form-build ref="kfb" :value="jsonData" :dynamic-data="dynamicData" />
      </div>
      <div v-if="value.indexOf('2')!=-1">
      <img :src="imageUrl" alt="流程图" class="image" />
    </div>
      <div v-if="value.indexOf('3')!=-1">
        <a-card
          class="card"
          title="审批流程"
          :bordered="false"
        >
          <!-- <FlowChartLine :process-instance-id="record.processInstanceId" /> -->
        </a-card>
        <a-card
          class="card"
          title="当前节点信息"
          :bordered="false"
          v-show="actData.length > 0"
        >
          <a-table
            :columns="actColumns"
            :data-source="actData"
            :pagination="false"
            bordered
          >
            <template slot="toberead" slot-scope="text, record, index">
              <div>
                <p v-for="(item, index) in record.tobereadList" :key="index">
                  {{ item.user_name }}({{
                    item.is_read == "0" ? "未读" : "已读"
                  }})
                </p>
              </div>
            </template>
          </a-table>
        </a-card>
        <a-card
          class="card"
          title="办理过程记录"
          :bordered="false"
          v-show="hisData.length > 0"
        >
          <a-table
            :columns="hisColumns"
            :data-source="hisData"
            :pagination="false"
            bordered
          >
            <template slot="toberead" slot-scope="text, record, index">
              <div>
                <p v-for="(item, index) in record.tobereadList" :key="index">
                  {{ item.user_name }}({{
                    item.is_read == "0" ? "未读" : "已读"
                  }})
                </p>
              </div>
            </template>
          </a-table>
        </a-card>
      </div>
    </div>
  </div>
</template>
<script>
import {
  findActivityList,
  findActivityTaskList,
} from '@/api/activiti/processTask'
import { findVFormInfo, findVDataInfo } from '@/api/customize/vdata'
import axios from 'axios'
import { formatDate } from '@/utils/date.js'
import FlowChartLine from '@/views/customize/vdata/FlowChartLine.vue'
import { testPrint } from '@/utils/dagprint.js'
import print from 'print-js'
const actColumns = [
  {
    title: '序号',
    dataIndex: '',
    customRender: function (t, r, index) {
      return parseInt(index) + 1
    },
  },
  {
    title: '环节名称',
    dataIndex: 'name',
    customRender: (text, row, index) => {
      if (text != null) {
        return text
      } else {
        return ''
      }
    },
  },
  {
    title: '当前办理人',
    dataIndex: 'assignee_name',
    customRender: (text, row, index) => {
      if (text != null) {
        return text
      } else {
        return ''
      }
    },
  },
  {
    title: '任务创建时间',
    dataIndex: 'createTime',
    customRender: (text, row, index) => {
      if (text != '' && text != null) {
        return formatDate(text)
      }
    },
  },
  {
    title: '办理状态',
    dataIndex: '',
    customRender: (text, row, index) => {
      if (row.assignee_name != null) {
        return '未完成'
      } else {
        if (row.claimTime == null) {
          return '未签收'
        } else {
          return '未完成（签收时间' + formatDate(row.claimTime);
          +'）'
        }
      }
    },
  },
  {
    title: '环节状态',
    dataIndex: 'suspensionState',
    ellipsis: true,
    customRender: (text, row, index) => {
      if (text == '1') {
        return '活跃状态'
      } else if (text == '2') {
        return '中断状态'
      }
    },
  },
//   {
//     title: "备注",
//     dataIndex: "owner_name",
//     ellipsis: true,
//     customRender: (text, row, index) => {
//       if (text != "" && text != null) {
//         return "所属人：" + text;
//       } else {
//         return "";
//       }
//     },
//   },
  {
    title: '待阅信息',
    dataIndex: 'toberead',
    scopedSlots: { customRender: 'toberead' },
    width: '140px',
  },
]

const hisColumns = [
  {
    title: '序号',
    dataIndex: '',
    customRender: function (t, r, index) {
      return parseInt(index) + 1
    },
  },
  {
    title: '环节类型',
    dataIndex: 'activityType',
    customRender: (text, row, index) => {
      if (text == 'startEvent') {
        return '开始节点'
      } else if (text == 'endEvent') {
        return '结束节点'
      } else if (text == 'userTask') {
        return '用户节点'
      } else {
        return '其他节点'
      }
    },
  },
  {
    title: '环节名称',
    dataIndex: 'activityName',
    customRender: (text, row, index) => {
      if (text != null) {
        return text
      } else {
        return ''
      }
    },
  },
  {
    title: '办理人',
    dataIndex: 'assignee_name',
    customRender: (text, row, index) => {
      if (text != null) {
        return text
      } else {
        return ''
      }
    },
  },
  {
    title: '办理意见',
    dataIndex: 'comment_msg',
    customRender: (text, row, index) => {
      if (text != null) {
        return text
      } else {
        return ''
      }
    },
  },
  {
    title: '办理开始时间',
    dataIndex: 'startTime',
    customRender: (text, row, index) => {
      if (text != '' && text != null) {
        return formatDate(text)
      }
    },
  },
  {
    title: '办理结束时间',
    dataIndex: 'endTime',
    customRender: (text, row, index) => {
      if (text != '' && text != null) {
        return formatDate(text)
      }
    },
  },
  {
    title: '待阅信息',
    dataIndex: 'toberead',
    scopedSlots: { customRender: 'toberead' },
    width: '140px',
  },
]

export default {
  // 声明当前子组件接收父组件传递的属性
  props: {
    record: {
      type: Object,
      default: null,
    },
  },
  data () {
    return {
      ApproveTimeline: [], // 流程时间线
      jsonData: {},
      form_data: {},
      dynamicData: this.record.dynamicData,
      form: {},
      initStatus: false,

      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      other: '',
      mybol: false,
      headers: {
        authorization: 'authorization-text',
      },
      uploading: false,
      form: {},
      cardList: [
        {
          key: 'form',
          tab: '表单',
        },
        {
          key: "flowchart",
          tab: "流程图",
        },
        {
          key: 'processTrack',
          tab: '流程跟踪单',
        },
      ],
      activeKey: 'form',
      imageUrl: '',
      hisData: [],
      hisColumns,
      actData: [],
      actColumns,
      value: ['1', '2', '3'],
    }
  },
  components: { FlowChartLine },
  mounted () {
    if (this.record.id != undefined) {
      this.form = this.record
      // 查询菜单配置信息
      this.jsonData = JSON.parse(this.record.table_content)
      this.initStatus = true
    } else {
      if (this.record.businessKey.indexOf('customize') != -1) {
        // 查询菜单配置信息
        const data = this.record.businessKey.split(':')
        this.initData(data[2])
      }
    }
    // 初始化流程图
    this.flowchart(this.record);
    // 查询流程办理节点信息
    this.activityList()
  },
  updated () {
    if (this.record.id != undefined) {
      // 查询编辑项内容
      if (this.form.id != '' && this.form.id != undefined) {
        this.$refs.kfb.setData(this.form)
        this.$refs.kfb.disableAll()
      } else {
        this.initStatus = true
      }
    } else {
      if (this.record.businessKey.indexOf('customize') != -1) {
        // 查询菜单配置信息
        const data = this.record.businessKey.split(':')
        this.initFormData(data[2], data[3])
      }
    }
  },
  methods: {

    initData (menu_id) {
      findVFormInfo({ menu_id: menu_id }).then((response) => {
        this.form_data = response.data.data
        this.dynamicData = response.data.object
        this.jsonData = JSON.parse(this.form_data.table_content)
      })
    },
    initFormData (menu_id, id) {
      findVDataInfo({
        table_id: this.record.formKey,
        menu_id: menu_id,
        id: id,
      }).then((response) => {
        this.form = response.data
        this.$refs.kfb.setData(response.data)
        this.initStatus = true
        this.$refs.kfb.disableAll()
        // findFormParams({
        //   nodeType: "nodeType",
        //   taskId: this.record.id,
        // }).then((response) => {
        //   this.visable = true;
        //   let data = response.data.data;
        //   if (data.writeFieldKey != undefined) {
        //     this.$refs.kfb.enable(data.writeFieldKey.split(","));
        //   }
        //   if (data.hideFieldKey != undefined) {
        //     this.$refs.kfb.hide(data.hideFieldKey.split(","));
        //     this.hideFieldKey = data.hideFieldKey;
        //   }
        // });
      })
    },
    onTabChange (key, activeKey) {
      this.activeKey = key
    },
    resetForm () {
      this.$refs.ruleForm.resetFields()
    },
    onOk () {
      return new Promise((resolve) => {
        resolve(true)
      })
    },
    onCancel () {
      return new Promise((resolve) => {
        resolve(true)
      })
    },
    activityList () {
      findActivityList({
        processInstanceId: this.record.processInstanceId,
      }).then((response) => {
        this.hisData = response.data.data.filter(
          (item) => item.endTime != null,
        )
      })

      findActivityTaskList({
        processInstanceId: this.record.processInstanceId,
      }).then((response) => {
        this.actData = response.data.data
      })
    },

    // 流程跟踪图带人和时间
    activitynodes () {
           findActivityNodes({
        processInstanceId: this.record.processInstanceId,
      }).then((response) => {
        this.ApproveTimeline = response.data.data
        console.log('shijianrenwu线', this.ApproveTimeline)
      })
    },

    flowchart (record) {
      this.visible = true
      axios({
        method: 'GET',
        url:
          process.env.VUE_APP_API_BASE_URL +
          '/activiti/processTask/readResource?processInstanceId=' +
          record.processInstanceId,
        responseType: 'arraybuffer',
      })
        .then((res) => {
          return (
            'data:image/svg+xml;base64,' +
            btoa(
              new Uint8Array(res.data).reduce(
                (data, byte) => data + String.fromCharCode(byte),
                '',
              ),
            )
          )
        })
        .then((res) => {
          this.imageUrl = res
        })
        .catch((e) => {
          if (e.toString().indexOf('429') !== -1) {
            this.$notification.warning({
              message: '请求超时,请稍后重试',
              description: '',
            })
          } else {
            this.$notification.warning({
              message: '获取流程图失败',
              description: '',
            })
          }
        })
    },
    printDiv () {
      const style = '@page {margin:0 10mm};'// 打印时去掉眉页眉尾
      // 打印为什么要去掉眉页眉尾？因为眉页title时打印当前页面的title，相当于是获取html中title标签里面的内容，但是比如我打印的内容只是一个弹框里面的内容，是没有title的，这时候就会出现undefined，为了避免出现这种情况，就可以隐藏眉页眉尾
      // printJS({
      //   printable: this.$refs.printDiv,// 标签元素id
      //   type: 'html',
      //   header: '',
      //   targetStyles: ['*'],
      //   style
      // });

      testPrint()

      //   printJS({
      //   printable: this.$refs.img,// 标签元素id
      //   type: 'html',
      //   header: '',
      //   targetStyles: ['*'],
      //   style
      // });

      // 各个配置项
      // printable:要打印的id。
      // type:可以是 html 、pdf、 json 等。
      // properties:是打印json时所需要的数据属性。
      // gridHeaderStyle和gridStyle都是打印json时可选的样式。
      // repeatTableHeader:在打印JSON数据时使用。设置为时false，数据表标题将仅在第一页显示。
      // scanStyles:设置为false时，库将不处理应用于正在打印的html的样式。使用css参数时很有用，此时自己设置的原来想要打印的样式就会失效，在打印预览时可以看到效果
      // targetStyles: [’*’],这样设置继承了页面要打印元素原有的css属性。
      // style:传入自定义样式的字符串，使用在要打印的html页面 也就是纸上的样子。
      // ignoreElements：传入要打印的div中的子元素id，使其不打印。非常好用
    },
  },
}
</script>
<style scoped>
.spin {
  text-align: center;
  border-radius: 4px;
  margin-bottom: 20px;
  padding: 30px 50px;
  margin: 40px 0;
}
table-tbody > tr > td {
  padding: 8px 16px !important;
}
.image{
  width: 100%;
}
.ca{
  display: none;
}
</style>
